<?php

namespace Modules\Asset\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

use Modules\Asset\Entities\Resale;
use \Modules\Asset\Entities\PackageSku;
use DB;

// 福袋资产
class Package extends Model
{
    protected $guarded = [];
    protected $table = 'package_assets';
    static public $resourceName = '';

    protected $appends = ['union_status', 'union_status_text'];

    protected $casts = [
        'reward' => 'json'
    ];

    public function getUnionStatusAttribute()
    {
        $map = [
            0 => 'pending',
            1 => 'opened',
            2 => 'resaled',
            3 => 'resale_pending'
        ];

        return @$map[$this->status] ?: 'unknow';
    }

    public function getUnionStatusTextAttribute()
    {
        $map = [
            'pending' => '待开盒',
            'opened' => '已开盒',
            'resaled' => '已转让',
            'resale_pending' => '转售中'
        ];

        return @v($map[$this->union_status], '未知状态');
    }

    // 状态筛选
    public function scopeStatus($query, $status)
    {
        $map = [
            'pending' => [
                'status' => 0
            ],
            'opened'  => [
                'status' => 1
            ],
            'resaled' => [
                'status' => 2
            ],
            'resale_pending' => [
                'status' =>  3
            ]
        ];

        $where = @$map[$status] ?: [
            'status' => 0
        ];

        return $query->where($where);
    }

    // 所属用户
    public function user() 
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    // 所有sku奖品
    public function skus()
    {
        return $this->hasMany('\Modules\Asset\Entities\PackageSku', 'package_asset_id');
    }

    // 根据订单创建福袋资源
    static public function createWith($order) 
    {
        DB::beginTransaction();

        $orderSku = $order->sku;

        // 抽奖次数 (开盲盒、一番赏等均定义为抽奖)
        $total = @$orderSku->total ?: 0;
        $title = @$orderSku->title;

        // \Log::error($order);

        $item = self::create([
            'title' => $title,
            'node_id' => $order->node_id,
            'node_type' => $order->node_type,
            'node_uuid' => $order->node_uuid,
            'node_money_price' => $orderSku->money_price,
            'node_score_price' => $orderSku->score_price,
            'activity_id' => $order->activity_id,
            'activity_type' => $order->activity_type,
            'activity_uuid' => $order->activity_uuid,
            'sku_total' => $orderSku->total,
            'user_id' => $order->user_id,
            'status' =>  0,
            'pay_order_id' => $order->id,
            'room_id' => @$order->options['room_id']
        ]);


        $node = $order->node;
        $user = $order->user;

        // 为$user抽出幸运sku
        $skuMaps = $node->pickLuckySkus($total, $user, $order);

        if (!$skuMaps) {
            DB::rollBack();
            return false;
        }

        // 开盒取出奖品
        $item->createSkus($skuMaps, $order);

        // 自动开盒
        $isAutoOpen = true;
        if ($isAutoOpen) {
            $item->openBox();
        }

        DB::commit();

        return $item;
    }

    // 开启此盒 
    public function openBox()
    {
        if ($this->union_status !== 'pending') {
            return false;
        }

        $this->update([
            'status' => 1
        ]);

        // 把创建盒子时所有删除隐藏起来的sku恢复
        // $this->skus()->withTrashed()->restore();

        foreach ($this->skus as $packageSku) {
            if ($packageSku->sku_type_text === 'virtual_asset') {
                $packageSku->pickVirtualAsset();
            }
        }
    }

    // 创建奖品
    public function createSkus($skuMaps, $order)
    {
        $user = $this->user;
        $package = $this;

        // 使用sku创建boxItem
        $list = array_map(function ($skuMap) use ($package, $user, $order) {
            $item = PackageSku::initWith($package, $skuMap, $user, $order);
            // 未开启前设置为已删除不可见
            // $item->deleted_at = now();
            return $item;
        }, $skuMaps);
        
        $this->skus()->saveMany($list);

        return true;
    }

    // 生成转售
    public function resale($moneyPrice, $scorePrice, $optoins =  [])
    {

        if ($this->union_status !== 'pending') {
            return false;
        }

        $this->update([
            'status' => 3
        ]);

        // 生成转售记录
        $record = Resale::create([
            'user_id' => $this->user_id,
            'package_id' => $this->id,
            'resale_type' => 'package',
            'money_price' => $moneyPrice,
            'score_price' => $scorePrice,
            'limit_phone' => @$optoins['limit_phone']
        ]);

        return $record;
    }

    public function updateReward($rewardInfo)
    {
        $reward = $this->reward ?: [];

        $reward = array_merge($reward, $rewardInfo);

        $this->update([
            'reward' => $reward
        ]);
    }
}
